import React from "react";
import ReactDOM from "react-dom";

// render props 模式

// 导入图片资源
import img from "./images/cat.jpg"

// 实现模型的复用
class Mouse extends React.Component{
    // 鼠标的位置
    state = {
        x: 0,
        y: 0
    }
    // 鼠标移动事件处理
    handleMouseMove = e => {
        this.setState({
            x: e.clientX,
            y: e.clientY
        })
    }

    // 监听鼠标移动事件
    componentDidMount(){
        window.addEventListener('mousemove', this.handleMouseMove)
    }

    render(){
        return (
            this.props.render(this.state) // 将state状态暴露出去,,通过props的方法
        )
    }
}

class App extends React.Component{
    render () {
        return (
            <div>
                <h1>render props 模式</h1>
                <Mouse render={(mouse) => { // 接收Mouse组件暴露出来的state，，mouse为接收到参数
                    return <p>鼠标位置：{mouse.x}, {mouse.y}</p>
                }} />


                {/* 猫抓老鼠的功能 */}
                <Mouse render={ (mouse) => {
                    return (
                    <img 
                        src={img} 
                        alt="猫" 
                        height="10"
                        width="50"
                        height="50"
                        style={{
                            position: "absolute",
                            top: mouse.y -25,
                            left: mouse.x - 25
                        }} />)
                }} />
            </div>
        )
    }
}

ReactDOM.render(<App />, document.getElementById('root'))
